package com.daJiao.client;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20190711.models.SendStatus;
import com.daJiao.constants.Constants;
import com.daJiao.exception.BusinessException;
import com.daJiao.properties.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * <p>Title:      SmsClient. </p>
 * <p>Description 发送短信工具类 </p>
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company:    医百科技有限公司 </p>
 *
 * @author <a href="yangwensheng@100doc.com.cn"/>杨文生</a>
 * @since 2021/3/1 17:38
 */
@Component
@Slf4j
public class SysSmsClient {

    @Resource
    private SmsProperties smsProperties;

    /**
     * 发送短信验证码
     * @param phoneNumbers String[]
     * @param templateId String
     * @param templateParams String[]
     */
    public void sendSms(String[] phoneNumbers,String templateId, String[] templateParams) {
        try {
            Credential cred = new Credential(smsProperties.getSecretId(), smsProperties.getSecretKey());
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setReqMethod("POST");
            httpProfile.setConnTimeout(60);
            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setSignMethod("HmacSHA256");
            SmsClient client = new SmsClient(cred, "", clientProfile);
            SendSmsRequest req = new SendSmsRequest();
            req.setSmsSdkAppid(smsProperties.getAppid());
            req.setSign(smsProperties.getSign());
            req.setTemplateID(templateId);
            req.setPhoneNumberSet(phoneNumbers);
            req.setTemplateParamSet(templateParams);
            SendSmsResponse res = client.SendSms(req);
            log.info("===> 发送短信返回结果为 result = {}",SendSmsResponse.toJsonString(res));
            SendStatus[] sendStatusSet = res.getSendStatusSet();
            if(!Constants.SEND_SMS_SUCCESS.equals(sendStatusSet[0].getCode())){
                throw new BusinessException("短信发送失败，" + sendStatusSet[0].getMessage());
            }
        } catch (TencentCloudSDKException e) {
            log.error("调用腾讯云发送短信异常," + e.getMessage());
            throw new BusinessException(e.getMessage());
        }
    }
}
